<template>
  <div class="rounded border border-solid border-color-split md:flex md:flex-row md:items-stretch md:h-120">
    <div class="md:w-3/5 flex flex-col">
      <div class="pt-2 px-2 sm:pt-4 sm:px-4 border-0 border-b border-color-split border-solid">
        <div class="pb-2 sm:pb-4">
          <a-input-search
            v-model:value="keyword"
            placeholder="收费员名称或工号关键字"
            :allow-clear="true"
            :maxlength="32"
            @search="keywordSearch"
          />
        </div>
      </div>
      <div class="flex-1 relative rounded overflow-hidden">
        <SlTable
          :class="{ 'ant-table-empty-noborder': tableData.length === 0 }"
          :columns="columns"
          :pagination="pagination"
          size="small"
          :data-source="tableData"
          :loading="tableLoading"
          row-key="id"
          :row-selection="{ selectedRowKeys: value, onSelect, getCheckboxProps, onSelectAll }"
          :custom-row="customRow"
          :search-model="searchModel"
        >
          <template #bodyCell="{ column, record }: BodyCellOptions<TollCollectorItem>">
            <EllipsisText v-if="column.dataIndex === 'tollCollector'" :max-len="10" :text="record.tollCollector" />
          </template>
        </SlTable>
      </div>
    </div>
    <div class="md:w-2/5 border-0 border-t md:border-t-0 md:border-l border-solid border-color-split flex flex-col">
      <div class="py-5.5 flex flex-row items-center pl-4 pr-4.5">
        <div class="flex-1">
          <span class="text-lg font-semibold text-color-header">{{ t("common.choosed") }}</span>
          <span class="text-color-secondary">({{ selectedUser.length }})</span>
        </div>
        <div class="text-red-400 cursor-pointer" @click="clearSelected">
          {{ t("common.clear") }}
        </div>
      </div>
      <div v-if="selectedUser.length > 0" class="flex-1 overflow-auto pl-4 pr-4.5">
        <div v-for="(el, i) in selectedUser" :key="el.id" class="flex flex-row items-center mb-4">
          <div class="flex-1 overflow-hidden">
            <span class="text-color-main">{{ el.tollCollector }}</span>
          </div>
          <div class="cursor-pointer w-10 text-right">
            <a @click="removeSelected(el, i)">{{ t("common.remove") }}</a>
          </div>
        </div>
      </div>
      <SlEmpty v-else />
    </div>
  </div>
</template>
<script setup lang="ts">
import { useI18n } from "/@/locales/useI18n";
import { nextTick, onMounted, ref, watch } from "vue";
import type { TollCollectorItem } from "/@/api/main/civilizedService/models";
import { useCURD } from "/@/hooks/useCURD";
import { Api } from "/@/api/main/civilizedService";
import { RequestMethodEnum } from "/@/api/req/httpEnum";
import type { SelectExpose } from "/@/types/components";
import type { BodyCellOptions } from "/@/types/antd";

const props = withDefaults(
  defineProps<{
    //所勾选的用户id数组 双向绑定
    value: number[];
    //不能选择的用户id数组
    disabledValue?: number[];
  }>(),
  {}
);
const emits = defineEmits(["update:value"]);
const { t } = useI18n();
/**
 * search
 */
const keyword = ref("");
function keywordSearch() {
  reloadTable({
    noName: keyword.value,
  });
}
/**
 * table
 */
const columns = ref([
  {
    title: "工号",
    dataIndex: "jobNo",
  },
  {
    title: "姓名",
    dataIndex: "tollCollector",
  },
]);
const { tableData, tableLoading, pagination, reloadTable, searchModel } = useCURD<TollCollectorItem>({
  getPageUrl: Api.tollCollectorsPage,
  loadOnMounted: true,
});
//table select
const selectedUser = ref<TollCollectorItem[]>([]);
function getCheckboxProps(record: TollCollectorItem) {
  if (props.disabledValue?.includes(record.id as number)) {
    return { disabled: true };
  }
}
function onSelectAll(selected: boolean, selectedRows: TollCollectorItem[], changeRows: TollCollectorItem[]) {
  onUserSelectAll(selected, selectedRows, changeRows, false);
}
function onSelect(record: TollCollectorItem, selected: boolean) {
  onUserSelect(record, selected);
}
function onUserSelectAll(
  selected: boolean,
  selectedRows: TollCollectorItem[],
  changeRows: TollCollectorItem[],
  isTree?: boolean
) {
  const copyValue = [...props.value];
  changeRows.forEach((record) => {
    toggleOne(selected, copyValue, record);
  });
  emits("update:value", copyValue);
}
function onUserSelect(record: TollCollectorItem, selected: boolean) {
  const copyValue = [...props.value];
  toggleOne(selected, copyValue, record);
  emits("update:value", copyValue);
}

function toggleOne(selected: boolean, copyValue: number[], record: TollCollectorItem) {
  let index = copyValue.indexOf(record.id as number);
  if (selected) {
    if (index === -1) {
      copyValue.push(record.id as number);
      selectedUser.value.push(record);
    }
  } else {
    if (index >= 0) {
      copyValue.splice(index, 1);
      selectedUser.value.splice(index, 1);
    }
  }
}
function customRow(record: TollCollectorItem) {
  return {
    onClick() {
      if (props.disabledValue?.includes(record.id as number)) {
        return;
      }
      onSelect(record, !props.value.includes(record.id as number));
    },
  };
}

/**
 * table select
 */
watch(
  () => props.value,
  (v) => {
    if (v.length === 0) {
      selectedUser.value = [];
    }
  }
);
function removeSelected(el, i) {
  const copyValue = [...props.value];
  const j = copyValue.indexOf(el.userId);
  if (j >= 0) {
    copyValue.splice(j, 1);
  }
  selectedUser.value.splice(i, 1);
  emits("update:value", copyValue);
}
function clearSelected() {
  emits("update:value", []);
}
/**
 * expose
 */
const myExpose: SelectExpose<TollCollectorItem> = {
  async reload() {
    keywordSearch();
  },
  reset() {
    // keyword.value = "";
    // keywordSearch();
    clearSelected();
  },
  getSelecedItems() {
    return selectedUser.value;
  },
  setSelectedItems(items) {
    selectedUser.value = items;
  },
};
defineExpose(myExpose);
</script>
<style lang="less">
.user-depart-tree {
  .ant-tree-checkbox {
    margin: 4px 4px 0;
  }
  .ant-tree-iconEle {
    width: 18px !important;
    margin-right: 5px;
  }
}
</style>
